package com.shisfish.library.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import com.shisfish.library.Impl.BookBorrowMessageImpl;
import com.shisfish.library.Impl.BookMessageImpl;
import com.shisfish.library.Model.BookBorrowMessage;
import com.shisfish.library.Model.BookMessage;
import com.shisfish.library.Utils.LoginUtils;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;

@Path("bookBorrowMessage")
public class BookBorrowMessageController extends GlobalVariable{

	BookBorrowMessageImpl bookBorrowMessageImpl = new BookBorrowMessageImpl();
	
	BookMessageImpl bookMessageImpl = new BookMessageImpl();
	
	@POST
	@Path("borrowABook/{idadmin}")
	@Produces("application/json; charset=utf-8")
	public String borrowABook(@PathParam("idadmin") String idadmin, @FormParam("barCode") String barCode, 
			@FormParam("isbn") String isbn, @FormParam("reader") String reader,
			@FormParam("loanid") String loanid, @Context HttpServletRequest request){
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (LoginUtils.isLoginAdmin(idadmin, request)) {
			
			List<BookMessage> bookMessages = bookMessageImpl.selectByKey(isbn);
			
			if (bookMessages.size() > 0) {
				BookMessage bookMessage = bookMessages.get(0);
				
				if(bookMessage.getSurplus() != 0 && bookMessage.getSurplus_show() != 0) {
					
					bookMessage.setSurplus(bookMessage.getSurplus()-1);
					bookMessage.setSurplus_show(bookMessage.getSurplus_show()-1);
					
					if(bookMessage.getSurplus() == 0) {
						bookMessage.setIsBespeak(1);
					}
					
					int flag_1 = bookMessageImpl.updateOne(bookMessage);
					
					if (flag_1 == 1) {
						globalMap.put("message", UPDATE_SUCCESS);
						
						BookBorrowMessage bookBorrowMessage = new BookBorrowMessage(barCode, isbn, idadmin, reader, loanid);
						
						int flag = bookBorrowMessageImpl.insertOne(bookBorrowMessage);
						
						if (flag == 1) {
							globalMap.put("message", ADD_SUCCESS);
						}
						else {
							globalMap.put("message", ADD_ERROR);
						}
						
					}
					else {
						globalMap.put("message", ADD_ERROR);
					}
					
				}
			}
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
}
